<template>
  <div class="homeView">
    <nav
      style="
        color: #ffffff;
        font-size: 40px;
        width: 100%;
        text-align: center;
        margin-bottom: 100px;
      "
    >
      {{ this.$appName }}
    </nav>
    <div>
      <div class="title">{{ title }}</div>
      <canvas ref="canvas" style="display: none"></canvas>
      <div class="content">
        <video class="videos" ref="video" autoplay></video>
      </div>
      <div>
        <button class="btn" @click="handleClick">点击进行身份证验证</button>
        <button class="btn" @click="goBack">返回首页</button>
      </div>
    </div>
  </div>
</template>
<script>
import $api from "../utils/api";
export default {
  data() {
    return {
      photoUrl: null,
      videoStream: null,
      data: null,
      showFlag: false,
      ifSendQuest: true,
      ifSendQuestExaminer: true,
      timer: null,
      title: "请进行考生识别",
      camerType: 0,
    };
  },
  created() {},
  mounted() {
    // 可以在mounted钩子中初始化相机，如果需要的话
    this.switchCamera();
    this.takePicture();
  },
  destroyed() {
    clearInterval(this.timer);
  },

  methods: {
    async openCamera() {
      try {
        const stream = await navigator?.mediaDevices?.getUserMedia({
          video: true,
        });
        this.$refs.video.srcObject = stream;
        this.videoStream = stream;
        this.showFlag = true;
      } catch (error) {
        console.error("Error accessing the camera: ", error);
      }
    },
    takePicture() {
      if (this.$route.name == "home" || this.$route.name == "examinerPage") {
        this.timer = setInterval(() => {
          const video = this.$refs.video;
          const canvas = this.$refs.canvas;
          const ctx = canvas.getContext("2d");
          if (this.videoStream) {
            // 将视频流的画面绘制到canvas上
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
            // 将canvas的内容转换为图片URL
            this.photoUrl = canvas.toDataURL("image/png");

            this.getPhoto(this.photoUrl);
          }
        }, 2000);
      }
    },
    getPhoto(baseDate) {
      let examinerId = localStorage.getItem("kgId");
      $api.getPhoto({ base64: baseDate, examinerId }).then((res) => {
        if (res.status == 200 && res.data.code == 200) {
          this.data = res.data.data;
          localStorage.setItem("data", JSON.stringify(this.data));
          localStorage.setItem(
            "status",
            JSON.stringify(this.data.examRecord.status)
          );
          this.ifSendQuest = false;
          this.$message({
            message: "考生识别成功！",
            type: "success",
            duration: 1000,
          });
          setTimeout(() => {
            switch (this.data.examRecord.workType) {
              case "R1":
                this.$router.push({
                  name: "YaLiRongQi",
                });
                break;
              case "P":
                this.$router.push({
                  name: "QiPingChongZhuang",
                });
                break;
              case "R3":
                this.$router.push({
                  name: "YangCangWeiHu",
                });
                break;
              case "R2":
                this.$router.push({
                  name: "YiDongChongZhuang",
                });
                break;
              case "Y2":
                this.$router.push({
                  name: "YouLeChangCaoZuo",
                });
                break;
              case "Y1":
                this.$router.push({
                  name: "YouLeChangXiuLi",
                });
                break;
              case "T":
                this.$router.push({
                  name: "DianTiXiuLi",
                });
                break;
              case "G1":
                this.$router.push({
                  name: "GongYeGuoLu",
                });
                break;
              case "S1":
                this.$router.push({
                  name: "KeYunSuoDaoXiuLi",
                });
                break;
              case "S2":
                this.$router.push({
                  name: "KeYunSuoDaoZuoYe",
                });
                break;
              case "Q2(限流动式起重机)":
                this.$router.push({
                  name: "Q2XianLiuDongShi",
                });
                break;
              case "Q2(限桥式起重机)":
                this.$router.push({
                  name: "Q2XianQiaoShi",
                });
                break;
              case "Q2限塔式":
                this.$router.push({
                  name: "Q2XianTashi",
                });
                break;
              case "14":
                this.$router.push({
                  name: "Q2XianTashi",
                });
                break;
              case "Q1":
                this.$router.push({
                  name: "Q1ZhiHui",
                });
                break;
              case "N2":
                this.$router.push({
                  name: "GuanGuangChe",
                });
                break;
              case "F":
                this.$router.push({
                  name: "AnQuanFaJiaoYan",
                });
                break;
              case "G2":
                this.$router.push({
                  name: "DianZhanGuoLuSiLu",
                });
                break;
              case "G3":
                this.$router.push({
                  name: "GuoLuShuiChuLi",
                });
                break;
            }
            this.ifSendQuest = true;
          }, 1000);
        } else if (res.data.msg !== "Index: 0, Size: 0") {
          this.$message({
            message: res.data.msg,
            type: "warning",
          });
        }
      });
    },
    handleClick() {
      this.$router.push({
        name: "sfzView",
      });
    },
    goBack() {
      this.$router.push({
        name: "examinerPage",
      });
    },
    switchCamera() {
      const mode = "environment";
      const video = this.$refs.video;
      // 定义一个变量 mode 并赋值为 "environment"，表示要使用后置摄像头。若 mode 为其他值，则使用前置摄像头。
      const constraints = {
        video: {
          facingMode:
            mode === "environment" ? { exact: "environment" } : "user",
        },
      };

      navigator.mediaDevices
        .getUserMedia(constraints)
        .then((stream) => {
          video.srcObject = stream;
          this.videoStream = stream;
          this.showFlag = true;
        })
        .catch((error) => {
          console.error("无法访问摄像头：", error);
          alert("无法访问摄像头，请检查权限或设备是否支持");
        });
    },
  },
};
</script>
<style scoped>
.homeView {
  width: 100vw;
  height: 100vh;
  background-image: url(../assets/keji1.png);
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
.title {
  font-size: 40px;
  width: 300px;
  height: 50px;
  color: #ffffff;
  text-align: center;
  margin: 30px auto;
}
.btn {
  width: 300px;
  height: 50px;
  border-radius: 10px;
  font-size: 25px;
  margin-top: 20px;
  margin-left: 50%;
  transform: translate(-50%);
  text-align: center;
  background: #efefef;
  line-height: 50px;
}
.content {
  text-align: center;
}
.videos,
.take_picture {
  width: 60%;
  transform: rotate(180deg);
}
.kgdl {
  width: 200px;
  height: 40px;
  margin-top: 20px;
  margin-left: 50%;
  transform: translate(-50%);
  text-align: center;
  background: #efefef;
  line-height: 40px;
}
</style>
